package com.invengo.library_rfid;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.SparseIntArray;


public class VoiceManager {

    private Context mContext;
    private static VoiceManager mVoiceManager = null;
    private SoundPool mSoundPool = null;
    private SparseIntArray mSoundPoolMap = new SparseIntArray();

    private void initSoundPool(Context context) {
        this.mContext = context;
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build();

        mSoundPool = new SoundPool.Builder()
                .setMaxStreams(5)
                .setAudioAttributes(audioAttributes)
                .build();
        mSoundPoolMap.append(DeviceContants.TAG_SOUND, mSoundPool.load(context, R.raw.tag, 1));
        mSoundPoolMap.append(DeviceContants.SUCCESS_SOUND, mSoundPool.load(context, R.raw.success, 1));
        mSoundPoolMap.append(DeviceContants.ERROR_SOUND, mSoundPool.load(context, R.raw.error, 1));
        mSoundPoolMap.append(DeviceContants.BEEP_SOUND, mSoundPool.load(context, R.raw.beep, 1));
    }

    private VoiceManager(Context context){
        initSoundPool(context);
    }

    public static synchronized VoiceManager getInstance(Context context){
        if(null == mVoiceManager){
            mVoiceManager = new VoiceManager(context);
        }
        return mVoiceManager;
    }

    public void playSound(final int sound, final int loop){
        AudioManager audioManager = (AudioManager) this.mContext.getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        final float volume = streamVolumeCurrent / streamVolumeMax;
        mSoundPool.play(mSoundPoolMap.get(sound), volume, volume, 1, loop, 1.0f);
    }

    public void playSuccessSound(){
        mVoiceManager.playSound(DeviceContants.SUCCESS_SOUND, DeviceContants.SOUND_NO_LOOP_MODE);
    }

    public void playBeep(){
        mVoiceManager.playSound(DeviceContants.BEEP_SOUND, DeviceContants.SOUND_NO_LOOP_MODE);
    }

    public void playFailureSound(){
        mVoiceManager.playSound(DeviceContants.ERROR_SOUND, DeviceContants.SOUND_NO_LOOP_MODE);
    }

}
